package controllers

import (
	"strings"

	"gitee.com/wolferhua/gostudy/mirror-site/conf"
	"github.com/astaxie/beego/httplib"
)

type MirrorController struct {
	BaseController
}

func (m *MirrorController) MirrorRender() {

	url := conf.MirrorUrl + m.Ctx.Input.URI()
	req := httplib.NewBeegoRequest(url, m.Ctx.Input.Method())
	referer := m.Ctx.Input.Header("Referer")
	if len(referer) > 0 {
		referer = strings.Replace(referer, m.Ctx.Input.Domain(), conf.MirrorHost, 0)
	}

	headers := map[string]string{
		"X-Forward-For": m.Ctx.Input.IP(),
		"Host":          conf.MirrorHost,
		"Referer":       m.Ctx.Input.Header("Referer"),
		"User-Agent":    m.Ctx.Input.Header("User-Agent"),
		"Accept":        m.Ctx.Input.Header("Accept"),
		//"Accept-Encoding": m.Ctx.Input.Header("Accept-Encoding"),
		"Accept-Language": m.Ctx.Input.Header("Accept-Language"),
	}

	for k, v := range headers {
		req.Header(k, v)
	}
	if len(m.Ctx.Input.RequestBody) > 0 {
		req.Body(m.Ctx.Input.RequestBody)
	}
	str, _ := req.String()
	rep, _ := req.Response()
	m.Ctx.Output.Header("Content-Type", rep.Header.Get("Content-Type"))

	str = strings.Replace(str, conf.MirrorHost, m.Ctx.Request.Host, -1)

	str = strings.Replace(str, "runoob.com", m.Ctx.Request.Host, -1)

	str = strings.Replace(str, "菜鸟教程", "小码侠", -1)
	str = strings.Replace(str, "菜鸟", "小码", -1)
	b := []byte(str)
	m.Ctx.Output.Body(b)
}
